package com.njupt.Array;

import java.util.*;
import java.util.stream.Stream;

public class RemoveDuplicates {

    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        int slowIndex = -1;
//        int fastIndex = -1;
        for (int i = 0; i < len-1; i++) {
            if(nums[i] == nums[i+1]){
                int count = 0;
                slowIndex = i+1;
//                fastIndex = i+1;
                for (int fastIndex = i+1; fastIndex < len; fastIndex++) {
                    if(nums[fastIndex] != nums[i+1]){
                        nums[slowIndex++] = nums[fastIndex];
                    }else {
                        count++;
                    }
                }
                len -=count;

            }
        }
        return slowIndex == -1?1:slowIndex;
    }

    public int removeDuplicates1(int[] nums){
        Set<Integer> integers = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            integers.add(nums[i]);
        }
        Stream<Integer> sorted = integers.stream().sorted();
        Iterator<Integer> iterator = sorted.iterator();
        int index= 0;
        while(iterator.hasNext()){
            nums[index++] = iterator.next();
        }
        return index;
    }

    /**
     * 双指针，遍历一遍就获得
     * @param nums
     * @return
     */
    public int removeDuplicates2(int[] nums){
        int len = nums.length;
        if(len==1){
            return 1;
        }

        int slow =1 ; int fast =1;
        while(fast < len){
            if(nums[fast] != nums[fast-1]){
                nums[slow++] = nums[fast];
            }
            fast++;
        }
        return slow;
    }

    public static void main(String[] args) {
        int[] nums = {0};
        RemoveDuplicates test = new RemoveDuplicates();
        System.out.println(test.removeDuplicates2(nums));
        System.out.println(Arrays.toString(nums));
    }
}
